<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\Product;
use app\model\ProductCategories as ProductCategoriesModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\response\Json;

class ProductCategories extends BaseController
{
    protected ProductCategoriesModel $model;

    public function initialize(): void
    {
        $this->model = new ProductCategoriesModel();
    }

    // 获取所有分类

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function index(): Json
    {
        $categories = $this->model->getAllCategories();
        return apiResponse(200,'success',$categories);
    }


    // 创建分类

    /**
     * @throws \Exception
     */
    public function save(Request $request): Json
    {
        $data = $request->post();
        $result = $this->model->createCategory($data);
        return apiResponse($result['code'],$result['message']);
    }

    // 更新分类
    public function update(Request $request, $id): Json
    {
        $data = $request->put();
        $result = $this->model->updateCategory($id, $data);
        return apiResponse($result['code'],$result['message']);
    }

    // 删除分类

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function delete($id): Json
    {
        $result = $this->model->deleteCategory($id);
        return apiResponse($result['code'],$result['message']);
    }
}